package xyz.leohan.mymvpdemo.http;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by leo on 2017/5/16.
 * 下载回掉接口
 */

public abstract class HttpDownloadCallBack implements Callback<ResponseBody> {
    private File file;
    private static final int MSG_PROGRESS = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_PROGRESS) {
                Bundle bundle = msg.getData();
                onProgress(bundle.getBoolean("done"), bundle.getLong("fileSizeDownloaded"), bundle.getLong("fileSize"));
            }
        }
    };

    public HttpDownloadCallBack(@NonNull String filePath) {
        file = new File(filePath);
        if (!file.getParentFile().exists()) {
            boolean success = file.getParentFile().mkdirs();
            if (!success) {
                throw new RuntimeException("can not create file path");
            }
        }
    }

    public abstract void onFailed(String msg);

    public abstract void onProgress(boolean done, long completeSize, long total);

    @Override
    public void onResponse(Call call, Response response) {

        if (response.isSuccessful()) {

            final ResponseBody body = (ResponseBody) response.body();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean done = false;
                    try {
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        byte[] fileReader = new byte[4096];

                        long fileSize = body.contentLength();
                        long fileSizeDownloaded = 0;
                        inputStream = body.byteStream();
                        outputStream = new FileOutputStream(file);
                        while (true) {
                            int read = inputStream.read(fileReader);

                            if (read == -1) {
                                break;
                            }

                            outputStream.write(fileReader, 0, read);

                            fileSizeDownloaded += read;
                            if (fileSizeDownloaded == fileSize) {
                                done = true;
                            }
                            Log.i("download", fileSizeDownloaded + "," + fileSize);
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("done", done);
                            bundle.putLong("fileSizeDownloaded", fileSizeDownloaded);
                            bundle.putLong("fileSize", fileSize);
                            msg.setData(bundle);
                            msg.what = MSG_PROGRESS;
                            handler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        onFailed(e.getMessage());
                    }
                }
            }).start();


        } else {
            onFailed(response.message());
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        onFailed(t.getMessage());
    }
}
